#!/bin/bash
set -e
set -o pipefail

PROJECT_ROOT=$(cd "$(dirname "$0")/.." && pwd)
SWIFT_PROJECT_PATH="$PROJECT_ROOT/Apps/CLI"

if command -v xcbeautify >/dev/null 2>&1; then
    USE_XCBEAUTIFY=1
else
    USE_XCBEAUTIFY=0
fi

pipe_build_output() {
    if [[ "$USE_XCBEAUTIFY" -eq 1 ]]; then
        xcbeautify "$@"
    else
        cat
    fi
}

# Parse arguments
CLEAN_BUILD=false
if [[ "$1" == "--clean" ]]; then
    CLEAN_BUILD=true
fi

# Only clean if requested
if [[ "$CLEAN_BUILD" == "true" ]]; then
    echo "🧹 Cleaning previous build artifacts..."
    rm -rf "$SWIFT_PROJECT_PATH/.build"
    (cd "$SWIFT_PROJECT_PATH" && swift package reset 2>/dev/null || true)
fi

echo "📦 Reading version from version.json..."
VERSION=$(node -p "require('$PROJECT_ROOT/version.json').version" 2>/dev/null || echo "3.0.0-dev")

echo "💉 Injecting version into Swift code..."
VERSION_SWIFT_PATH="$SWIFT_PROJECT_PATH/Sources/PeekabooCLI/Version.swift"
if [[ ! -f "$VERSION_SWIFT_PATH" ]]; then
    VERSION_SWIFT_PATH="$SWIFT_PROJECT_PATH/Sources/peekaboo/Version.swift"
fi

# Get git information
GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
GIT_COMMIT_DATE=$(git show -s --format=%ci HEAD 2>/dev/null || echo "unknown")
GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
GIT_DIRTY=$(git diff --quiet && git diff --cached --quiet || echo "-dirty")
BUILD_DATE=$(date -Iseconds)

# Check if Version.swift exists and has the same git commit
NEEDS_UPDATE=true
if [[ -f "$VERSION_SWIFT_PATH" ]]; then
    EXISTING_COMMIT=$(grep "gitCommit = " "$VERSION_SWIFT_PATH" 2>/dev/null | sed 's/.*gitCommit = "\(.*\)".*/\1/' || echo "")
    if [[ "$EXISTING_COMMIT" == "$GIT_COMMIT$GIT_DIRTY" ]]; then
        # Same commit, preserve existing build date to avoid triggering rebuilds
        BUILD_DATE=$(grep "buildDate = " "$VERSION_SWIFT_PATH" 2>/dev/null | sed 's/.*buildDate = "\(.*\)".*/\1/' || echo "$BUILD_DATE")
        NEEDS_UPDATE=false
    fi
fi

# Only update if git commit changed or file doesn't exist
if [[ "$NEEDS_UPDATE" == "true" || ! -f "$VERSION_SWIFT_PATH" ]]; then
    cat > "$VERSION_SWIFT_PATH" << EOF
// This file is auto-generated by the build script. Do not edit manually.
enum Version {
    static let current = "Peekaboo $VERSION"
    static let gitCommit = "$GIT_COMMIT$GIT_DIRTY"
    static let gitCommitDate = "$GIT_COMMIT_DATE"
    static let gitBranch = "$GIT_BRANCH"
    static let buildDate = "$BUILD_DATE"
    
    static var fullVersion: String {
        return "\(current) (\(gitBranch)/\(gitCommit), built: \(buildDate))"
    }
}
EOF
else
    echo "   Version.swift is up-to-date (commit: $GIT_COMMIT$GIT_DIRTY)"
fi

if [[ "$CLEAN_BUILD" == "true" ]]; then
    echo "🏗️ Building for debug (clean build)..."
else
    echo "🏗️ Building for debug (incremental)..."
fi

(
    cd "$SWIFT_PROJECT_PATH"
    swift build 2>&1 | pipe_build_output
)

echo "🔏 Code signing the debug binary..."
PROJECT_NAME="peekaboo"
DEBUG_BINARY_PATH="$SWIFT_PROJECT_PATH/.build/debug/$PROJECT_NAME"
ENTITLEMENTS_PATH="$SWIFT_PROJECT_PATH/Sources/Resources/peekaboo.entitlements"

if [[ -f "$ENTITLEMENTS_PATH" ]]; then
    codesign --force --sign - \
        --identifier "boo.peekaboo" \
        --entitlements "$ENTITLEMENTS_PATH" \
        "$DEBUG_BINARY_PATH"
    echo "✅ Debug binary signed with entitlements"
else
    echo "⚠️  Entitlements file not found, signing without entitlements"
    codesign --force --sign - \
        --identifier "boo.peekaboo" \
        "$DEBUG_BINARY_PATH"
fi

echo "📦 Copying binary to project root..."
cp "$DEBUG_BINARY_PATH" "$PROJECT_ROOT/peekaboo"
echo "✅ Debug build complete"
